import { useState, useEffect } from 'react';
import { PlusOutlined } from '@ant-design/icons';
import styles from './calendar.module.css';

function App() {
  const [currentMonth, setCurrentMonth] = useState(new Date().getMonth());
  const [currentYear, setCurrentYear] = useState(new Date().getFullYear());
  const [currentDate, setCurrentDate] = useState(new Date());
  const [showModal, setShowModal] = useState(false);
  const [eventTitle, setEventTitle] = useState('');
  const [eventContent, setEventContent] = useState('');
  const [eventType, setEventType] = useState('orange');
  const [startDate, setStartDate] = useState(new Date());
  const [endDate, setEndDate] = useState(new Date());
  const [startTime, setStartTime] = useState('09:40');
  const [endTime, setEndTime] = useState('10:00');
  const [currentView, setCurrentView] = useState('month'); // 默认为本月视图
  const [events, setEvents] = useState([]); // 新增状态来存储所有事件
  const [showEventDetail, setShowEventDetail] = useState(false);
  const [selectedEvent, setSelectedEvent] = useState(null);
  const [monthlyEvents, setMonthlyEvents] = useState([]);

  // 获取某月的天数
  const getDaysInMonth = (month, year) => {
    return new Date(year, month + 1, 0).getDate();
  };

  // 获取某月的第一天是周几
  const getFirstDayOfMonth = (month, year) => {
    return new Date(year, month, 0).getDay();
  };

  // 生成日历数据
  const generateCalendar = () => {
    const daysInMonth = getDaysInMonth(currentMonth, currentYear);
    const firstDay = getFirstDayOfMonth(currentMonth, currentYear);
  
    let calendarData = [];
    if (currentView === 'month') {
      for (let i = 0; i < 6; i++) {
        const week = [];
        for (let j = 0; j < 7; j++) {
          const dayIndex = i * 7 + j - firstDay;
          if (dayIndex >= 0 && dayIndex < daysInMonth) {
            const date = dayIndex + 1;
            const eventsForDate = events.filter(event => {
              const eventStartDate = new Date(event.startDate);
              const eventEndDate = new Date(event.endDate);
              return (
                eventStartDate.getFullYear() === currentYear &&
                eventStartDate.getMonth() === currentMonth &&
                eventStartDate.getDate() === date
              ) || (
                eventEndDate.getFullYear() === currentYear &&
                eventEndDate.getMonth() === currentMonth &&
                eventEndDate.getDate() === date
              );
            });
            week.push({
              date,
              events: eventsForDate,
              hasEvent: eventsForDate.length > 0 // 添加 hasEvent 标识
            });
          } else {
            week.push(null);
          }
        }
        calendarData.push(week);
      }
    } else if (currentView === 'week') {
      // 生成本周的日历数据
  
      // 找到本周的周日
      const startOfWeek = new Date(currentYear, currentMonth, currentDate.getDate() - currentDate.getDay());
      const weekDates = [];
  
      for (let i = 0; i < 7; i++) {
        const date = new Date(startOfWeek);
        date.setDate(startOfWeek.getDate() + i + 1);
        weekDates.push(date);
      }
  
      // 创建本周的日历数据
      let week = [];
      for (let i = 0; i < 7; i++) {
        const date = weekDates[i];
        week.push({
          date: date.getDate(),
          month: date.getMonth(),
          year: date.getFullYear(),
          events: [],
          hasEvent: false // 初始化 hasEvent 为 false
        });
      }
  
      // 如果本周的周末排在了第二行，则在第二行的第一个格子写入日期
      if (week[6].date > daysInMonth) {
        calendarData.push([null, null, null, null, null, null, null]); // 第一行为空
        calendarData.push(week); // 第二行为本周数据
      } else {
        calendarData.push(week); // 第一行为本周数据
      }
    } else if (currentView === 'day') {
      // 生成当日的日历数据
      const today = new Date(currentYear, currentMonth, currentDate.getDate());
      const dayOfWeek = today.getDay(); // 获取今天是周几（0-6，0表示周日）
  
      // 创建一个包含当天日期的数组，并填充其他位置为 null
      calendarData = [
        [null, null, null, null, null, null, null], // 第一行为空
        [null, null, null, null, null, null, null]  // 第二行为本周数据
      ];
  
      // 在第二行的对应位置插入当日数据
      calendarData[1][dayOfWeek] = {
        date: today.getDate(),
        month: today.getMonth(),
        year: today.getFullYear(),
        events: [],
        hasEvent: false // 初始化 hasEvent 为 false
      };
    }

    calendarData.forEach(week => {
      week.forEach(day => {
        if (day) {
          day.events = events.filter(event => {
            const eventStartDate = new Date(event.startDate);
            const eventEndDate = new Date(event.endDate);
            return (
              eventStartDate.getFullYear() === day.year &&
              eventStartDate.getMonth() === day.month &&
              eventStartDate.getDate() === day.date
            ) || (
              eventEndDate.getFullYear() === day.year &&
              eventEndDate.getMonth() === day.month &&
              eventEndDate.getDate() === day.date
            );
          });
          day.hasEvent = day.events.length > 0; // 更新 hasEvent 标识
        }
      });
    });
  
    return calendarData;
  };
  
  const [calendarData, setCalendarData] = useState(generateCalendar());  

  useEffect(() => {
    const newCalendarData = generateCalendar();
    setCalendarData(newCalendarData);
  }, [events, currentMonth, currentYear, currentView]);

  const handlePrevMonth = () => {
    if (currentMonth === 0) {
      setCurrentMonth(11);
      setCurrentYear(currentYear - 1);
    } else {
      setCurrentMonth(currentMonth - 1);
    }
  };

  const handleNextMonth = () => {
    if (currentMonth === 11) {
      setCurrentMonth(0);
      setCurrentYear(currentYear + 1);
    } else {
      setCurrentMonth(currentMonth + 1);
    }
  };

  const handleThisMonth = () => {
    setCurrentView('month');
    const today = new Date();
    setCurrentMonth(today.getMonth());
    setCurrentYear(today.getFullYear());
  
    // 生成本月的事件列表
    const currentMonthEvents = events.filter(event => {
      const eventDate = new Date(event.startDate);
      return (
        eventDate.getFullYear() === today.getFullYear() &&
        eventDate.getMonth() === today.getMonth()
      );
    });
  
    setMonthlyEvents(currentMonthEvents);
  };

  const handleThisWeek = () => {
    setCurrentView('week');
    const now = new Date();
    const dayOfWeek = now.getDay(); // 获取今天是周几（0-6，0表示周日）
    let startOfWeek = new Date(now);
  
    // 如果今天不是周日，则找到本周的周日
    if (dayOfWeek !== 0) {
      startOfWeek.setDate(now.getDate() - dayOfWeek);
    }
  
    setCurrentDate(startOfWeek);
    setCurrentMonth(startOfWeek.getMonth());
    setCurrentYear(startOfWeek.getFullYear());
  };

  const handleMonthChange = (event) => {
    const selectedMonth = event.target.value;
    setCurrentMonth(selectedMonth - 1);
  };

  const handleYearChange = (event) => {
    const selectedYear = event.target.value;
    setCurrentYear(selectedYear);
  };

  const handleAddEventClick = () => {
    setShowModal(true);
  };

  const handleCloseModal = () => {
    setShowModal(false);
    setEventTitle('');
    setEventContent('');
    setEventType('orange');
    setStartDate(new Date());
    setEndDate(new Date());
    setStartTime('09:40');
    setEndTime('10:00');
  };

  const handleAddEvent = () => {
    const newEvent = {
      title: eventTitle,
      content: eventContent,
      type: eventType,
      startDate: new Date(startDate.toISOString().split('T')[0] + 'T' + startTime),
      endDate: new Date(endDate.toISOString().split('T')[0] + 'T' + endTime),
    };
  
    let events = JSON.parse(localStorage.getItem('events')) || [];
    events.push(newEvent);
    localStorage.setItem('events', JSON.stringify(events));
    setEvents([...events]);
    handleCloseModal();
  };

  return (
    <div className={styles.calendar}>
      <div className={styles.calendarHeader}>
        <div className={styles.breadcrumb}>
          <span>🏠</span>
          <span>&gt;</span>
          <span>日历</span>
        </div>
        <nav className={styles.calendarNav}>
          <button 
            onClick={handleThisMonth} 
            className={`${styles.navButton} ${currentView === 'month' ? styles.active : ''}`}
          >
            本月
          </button>
          <button 
            onClick={handleThisWeek} 
            className={`${styles.navButton} ${currentView === 'week' ? styles.active : ''}`}
          >
            本周
          </button>
        </nav>
        <div className={styles.calendarMonthYearDisplay}>
          {currentYear}年 {currentMonth + 1}月
        </div>
        <div className={styles.calendarMonthYearSelector}>
          <button className={styles.calendarNavBtn} onClick={handlePrevMonth}>
            {'<'}
          </button>
          <span>
            <select value={currentMonth + 1} onChange={handleMonthChange}>
              {Array.from({ length: 12 }, (_, i) => (
                <option key={i} value={i + 1}>
                  {i + 1}月
                </option>
              ))}
            </select>
            <select value={currentYear} onChange={handleYearChange}>
              {Array.from({ length: 20 }, (_, i) => (
                <option key={i} value={2024 + i}>
                  {2024 + i}
                </option>
              ))}
            </select>
          </span>
          <button className={styles.calendarNavBtn} onClick={handleNextMonth}>
            {'>'}
          </button>
          <button className={styles.addEventBtn} onClick={handleAddEventClick}><PlusOutlined /></button>
        </div>
      </div>
      <table className={styles.calendarTable}>
        <thead>
          <tr>
            <th>周一</th>
            <th>周二</th>
            <th>周三</th>
            <th>周四</th>
            <th>周五</th>
            <th>周六</th>
            <th>周日</th>
          </tr>
        </thead>
        <tbody>
          {calendarData.map((week, weekIndex) => (
            <tr key={weekIndex}>
              {week.map((day, dayIndex) => (
                <td key={dayIndex} className={day ? '' : styles.empty}>
                  {day && (
                    <>
                      <div className={styles.calendarDay}>{day.date}</div>

                      {/* 显示红点 */}
                      {day.hasEvent && (
                        <div 
                          className={styles.eventDot} 
                          onClick={() => {
                            setSelectedEvent(day.events[0]);
                            setShowEventDetail(true);
                          }}
                        ></div>
                      )}
                      
                      {day.events.map((event, eventIndex) => (
                        <div
                          key={eventIndex}
                          className={styles.calendarEvent}
                          style={{
                            background: event.type === 'orange' ? 'orange' : 
                                      event.type === 'red' ? 'red' : 
                                      event.type === 'cyan' ? 'cyan' : 
                                      event.type === 'green' ? 'green' : 'transparent',
                            width: `calc(100% * ${(event.endDate - event.startDate) / 86400000})`
                          }}
                        ></div>
                      ))}
                    </>
                  )}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>

      {/* 添加事件模态框 */}
      {showModal && (
        <div className={styles.modalOverlay}>
          <div className={styles.modalContent}>
            <div className={styles.modalHeader}>
              <h2>添加事件</h2>
              <button className={styles.modalClose} onClick={handleCloseModal}>×</button>
            </div>
            <div className={styles.modalBody}>
              <div>
                <label>标题</label>
                <input
                  type="text"
                  value={eventTitle}
                  onChange={(e) => setEventTitle(e.target.value)}
                  placeholder="新事件"
                />
              </div>
              <div>
                <label>内容</label>
                <textarea
                  value={eventContent}
                  onChange={(e) => setEventContent(e.target.value)}
                  placeholder="给订单编号 #238907开发票"
                ></textarea>
              </div>
              <div>
                <label>事件类型</label>
                <div className={styles.eventTypeSelector}>
                  <div
                    className={`${styles.eventType} ${styles.eventTypeOrange} ${eventType === 'orange' ? styles.eventTypeSelected : ''}`}
                    onClick={() => setEventType('orange')}
                  ></div>
                  <div
                    className={`${styles.eventType} ${styles.eventTypeRed} ${eventType === 'red' ? styles.eventTypeSelected : ''}`}
                    onClick={() => setEventType('red')}
                  ></div>
                  <div
                    className={`${styles.eventType} ${styles.eventTypeCyan} ${eventType === 'cyan' ? styles.eventTypeSelected : ''}`}
                    onClick={() => setEventType('cyan')}
                  ></div>
                  <div
                    className={`${styles.eventType} ${styles.eventTypeGreen} ${eventType === 'green' ? styles.eventTypeSelected : ''}`}
                    onClick={() => setEventType('green')}
                  ></div>
                </div>
              </div>
              <div>
                <label>开始日期</label>
                <input
                  type="date"
                  value={startDate.toISOString().split('T')[0]}
                  onChange={(e) => setStartDate(new Date(e.target.value))}
                />
              </div>
              <div>
                <label>结束日期</label>
                <input
                  type="date"
                  value={endDate.toISOString().split('T')[0]}
                  onChange={(e) => setEndDate(new Date(e.target.value))}
                />
              </div>
              <div>
                <label>开始时间</label>
                <input
                  type="time"
                  value={startTime}
                  onChange={(e) => setStartTime(e.target.value)}
                />
              </div>
              <div>
                <label>结束时间</label>
                <input
                  type="time"
                  value={endTime}
                  onChange={(e) => setEndTime(e.target.value)}
                />
              </div>
            </div>
            <div className={styles.modalFooter}>
              <button className={styles.modalAddBtn} onClick={handleAddEvent}>+ 添加事件</button>
            </div>
          </div>
        </div>
      )}

      {/* 事件详情弹窗 */}
      {showEventDetail && selectedEvent && (
        <div className={styles.modalOverlay} onClick={() => setShowEventDetail(false)}>
          <div className={styles.eventDetailModal} onClick={(e) => e.stopPropagation()}>
            <h3>{selectedEvent.title}</h3>
            <p><strong>内容：</strong>{selectedEvent.content}</p>
            <p><strong>时间：</strong>
              {new Date(selectedEvent.startDate).toLocaleString()} - {new Date(selectedEvent.endDate).toLocaleString()}
            </p>
            <button onClick={() => setShowEventDetail(false)}>关闭</button>
          </div>
        </div>
      )}

      {currentView === 'month' && (
        <div className={styles.eventList}>
          <h2>本月事件</h2>
          <ul>
            {monthlyEvents.map((event, index) => (
              <li key={index} className={styles.eventItem}>
                <div className={styles.eventDot} style={{ backgroundColor: event.type }}></div>
                <span>{event.title}</span>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}

export default App;